package com.borya.service.mobile.impl;

import com.alibaba.fastjson.JSONObject;
import com.borya.constant.RedisConstant;
import com.borya.dao.*;
import com.borya.filter.auth.AppSignTokenVersion;
import com.borya.framework.annotation.Autowired;
import com.borya.framework.annotation.Component;
import com.borya.framework.core.ServerRequest;
import com.borya.framework.util.ObjectUtils;
import com.borya.model.db.Flag;
import com.borya.model.db.JobNumberAudit;
import com.borya.model.db.Merchant;
import com.borya.model.db.User;
import com.borya.model.entity.*;
import com.borya.model.enumcation.OtherConfType;
import com.borya.service.impl.BaseServiceImpl;
import com.borya.service.mobile.SdkAppJobNumberService;
import com.borya.statuscode.StatusCode;
import com.borya.util.Constant;
import com.borya.util.DateUtils;
import com.borya.util.StringUtil;
import com.borya.util.SystemConfig;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.math.BigDecimal;
import java.time.Clock;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Component("sdkAppJobNumberServiceImpl")
public class SdkAppJobNumberServiceImpl extends BaseServiceImpl implements SdkAppJobNumberService {

    public Logger log = Logger.getLogger(getClass());

    @Autowired("sdkAppJobNumberDaoImpl")
    private SdkAppJobNumberDao sdkAppJobNumberDao;
    @Autowired("merchantDAO")
    private MerchantDAO merchantDAO;
    @Autowired("blackIdCardDAO")
    private BlackIdCardDAO blackIdCardDAO;
    @Autowired("userDAOImpl")
    private UserDAO userDAO;
    @Autowired("appConfDAOImpl")
    private AppConfDAO appConfDAO;

    @Override
    public String getJobNumberUserList(JSONObject json, ServerRequest request) {
        HeaderEntity authHeader = (HeaderEntity)request.getAttribute("boryaAuth");
        User user = (User)request.getAttribute("user");
        UserToken ut = (UserToken)request.getAttribute("userToken");

        String osType = String.valueOf(authHeader.getOsType());
        Integer appVersion = authHeader.getAppVersion();
        String appType = authHeader.getAppType();

        int backgroundVersion = getBackgroundVersion(appType, osType);
        SystemConfig instance = SystemConfig.getInstance();
        // IOS老版本不需要展示列表
        if (appVersion < backgroundVersion) {
            log.warn("app 版本低于服务器版本,appVersion=" + authHeader.getAppVersion() + ",serverVersion="
                    + instance.getInteger(AppSignTokenVersion.KA_MENG_IOS.getToken()));
            return StatusCode.NO_REGIST_ERR.toJSON("该功能正在维护,敬请期待。");
        }

        JSONObject jsonObject = new JSONObject();
        final String merchantId = user.getMerchantId();
        if (user.getIsMain() != 1) {
            log.warn("不是主账号不能查看子账号信息");
            return StatusCode.FORBID.toJSON("子账号不能查看列表信息");
        }

        List<UserDataModel> userList = sdkAppJobNumberDao.getJobNumberUserList(merchantId);
        if (Objects.isNull(userList) || 0 == userList.size()) {
            log.error("DB connection exception.");
            return StatusCode.SYSTEM_EXCEPTION.toJSON();
        }
        List<JobNumberAuditModel> auditList = sdkAppJobNumberDao.getJobNumberAuditList(merchantId, 1);
        jsonObject.put("auditList", auditList);
        jsonObject.put("userList", userList);

        Merchant merchant = merchantDAO.getByMerchantId(user.getMerchantId());
        if (Objects.isNull(merchant)) {
            log.error("DB 连接异常,merchantId=" + user.getMerchantId());
            return StatusCode.SYSTEM_EXCEPTION.toJSON();
        }

        int count;
        String appId = ut.getAppId();
        //根据appId去tb_sdk_app_conf表查询对应app配置的工号限制数量(企业、个人之分)
        JobNumberCountInfo info = sdkAppJobNumberDao.getJobNumberCountInfo(appId);
        if (ObjectUtils.isNull(info.getCompanyJobNumberCount())
                || ObjectUtils.isNull(info.getPersonalJobNumberCount())) {
            return StatusCode.SYSTEM_CONFIG_ERROR.toJSON();
        }
        if (1 == merchant.getMerchantType()) {
            //商户属性  1 企业 2 个人
            count = Integer.valueOf(info.getCompanyJobNumberCount()) - 1;
        } else {
            count = Integer.valueOf(info.getPersonalJobNumberCount()) - 1;
        }
        jsonObject.put("hintCont", String.format(Constant.HINT_CONT, count));
        jsonObject.put("sonJobNum", String.valueOf(count));

        return StatusCode.SUCCESS.toDiyJson("data", jsonObject);

    }

    @Override
    public String getManageLogList(User user) {
        final String dealerId = user.getDealerId();
        if (user.getIsMain() != 1) {
            log.warn("不是主账号不能查看管理日志信息");
            return StatusCode.FORBID.toJSON("子账号不能查看管理日志信息");
        }
        List<ManageLogModel> manageLogList = sdkAppJobNumberDao.getManageLogList(dealerId);
        if (Objects.isNull(manageLogList) || 0 == manageLogList.size()) {
            log.warn("manageLogList is null,dealerId is " + dealerId);
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", manageLogList);
        return StatusCode.SUCCESS.toDiyJson("data", jsonObject);
    }

    @Override
    public String createUser(ServerRequest request) {
        JSONObject json = (JSONObject)request.getAttribute("json");
        User user = (User)request.getAttribute("user");
        UserToken ut = (UserToken)request.getAttribute("userToken");
        String appId = ut.getAppId();
        int detailType = user.getDetailType();
        final String phone = json.getString("phone");
        if (StringUtils.isBlank(phone) || phone.length() != 11) {
            return StatusCode.PARAM_ERROR.toJSON("电话号码错误");
        }
        StringBuilder sb = new StringBuilder(RedisConstant.CREATE_USER);
        sb.append(phone).append(":appid:").append(appId);
        final String keyLock = sb.toString();
        sb = null;
        if (!sdkAppJobNumberDao.redis_setNx(keyLock, "1")) {
            log.warn("并发请求，" + json);
            return StatusCode.CONDITION_DEL_ING.json().msg("操作过快，请稍后再试").toString();
        }
        sdkAppJobNumberDao.redis_expire(keyLock, 120);
        try {
            final String name = json.getString("name");
            final String idCard = json.getString("idCard");
            final String idAddress = json.getString("idAddress");
            final String period = json.getString("period");
            final String cityCode = json.getString("cityCode");
            final String cityName = json.getString("cityName");
            final String relationType = json.getString("relationType");
            final String identifyPhotoFront = json.getString("identifyPhotoFront");
            final String identifyPhotoReverse = json.getString("identifyPhotoReverse");
            final String identifyPhotoHand = json.getString("identifyPhotoHand");
            final String identifyPhotoHead = json.getString("identifyPhotoHead");
            final String signPicture = json.getString("signPicture");
            final String reqCode = json.getString("code");
            //final String osType = json.getString("osType");

            if (StringUtils.isBlank(idCard)) {
                return StatusCode.PARAM_ERROR.json().msg("证件号未上传").toString();
            }
            if (StringUtils.isBlank(idAddress)) {
                return StatusCode.PARAM_ERROR.json().msg("证件地址未上传").toString();
            }
            if (StringUtils.isBlank(name)) {
                return StatusCode.PARAM_ERROR.toJSON("开户姓名错误");
            }
            if (StringUtils.isBlank(reqCode)) {
                return StatusCode.PARAM_ERROR.toJSON("验证码错误");
            }
            if (StringUtils.isBlank(cityCode)) {
                return StatusCode.PARAM_ERROR.toJSON("参数 城市编码 错误");
            }
            if (StringUtils.isBlank(cityName)) {
                return StatusCode.PARAM_ERROR.toJSON("参数 城市名 错误");
            }
            if (StringUtils.isBlank(relationType)) {
                return StatusCode.PARAM_ERROR.json().msg("关系类型未上传").toString();
            }
            if (StringUtils.isBlank(identifyPhotoFront)) {
                return StatusCode.PARAM_ERROR.json().msg("身份证正面照未上传").toString();
            }
            if (StringUtils.isBlank(identifyPhotoReverse)) {
                return StatusCode.PARAM_ERROR.json().msg("身份证背面照未上传").toString();
            }
            if (StringUtils.isBlank(identifyPhotoHand)) {
                return StatusCode.PARAM_ERROR.json().msg("手持证件照未上传").toString();
            }
            if (StringUtils.isBlank(identifyPhotoHead)) {
                return StatusCode.PARAM_ERROR.json().msg("身份证大头照未上传").toString();
            }
            if (StringUtils.isBlank(signPicture)) {
                return StatusCode.PARAM_ERROR.json().msg("签名图片未上传").toString();
            }
            if (user.getIsMain() != 1) {
                return StatusCode.PERMISSIONPROFILE_IS_NULL.toJSON();
            }
            String key = user.getUserId() + phone;
            String code = sdkAppJobNumberDao.redis_get(RedisConstant.REDIS_NAME_SPACE + key);
            if (StringUtils.isBlank(code)) {
                return StatusCode.CAPTCHE_NOT_FOUND.toJSON("验证码已失效，请重新获取");
            }
            if (ObjectUtils.nonEqual(code, reqCode)) {
                return StatusCode.CAPTCHE_NOT_FOUND.toJSON("验证码错误");
            }

            Merchant merchant = merchantDAO.getByMerchantId(user.getMerchantId());
            if (Objects.isNull(merchant)) {
                log.error("DB 连接异常,merchantId=" + user.getMerchantId());
                return StatusCode.SYSTEM_EXCEPTION.toJSON();
            }

            // 校验存在几个工号(包括在途、主工号)
            String checkSonJobNumCount = checkSonJobNumCount(user.getMerchantId(), merchant.getMerchantType(),appId);
            if (StringUtils.isNotBlank(checkSonJobNumCount)) {
                return checkSonJobNumCount;
            }

            if(detailType == 1){
                // 校验身份证是否黑名单
                String checkIdCardBlack = checkIdCardIsBlack(idCard);
                if (StringUtils.isNotBlank(checkIdCardBlack)) {
                    return checkIdCardBlack;
                }
            }

            //校验该手机号是否在本app平台已经注册过。自己已经是主工号了，不能申请成为另外一个商户的子工号。
            User userDB = sdkAppJobNumberDao.getJobnumberUserByPhone(phone,detailType);
            String checkPhone = checkPhone(phone, userDB);
            if (StringUtils.isNotBlank(checkPhone)) {
                return checkPhone;
            }

            // 校验手机号是否已经注册过（在途，该子工号手机号是否正在审核中）
            String checkPhoneByState = checkPhoneZaiTu(phone,detailType);
            if (StringUtils.isNotBlank(checkPhoneByState)) {
                return checkPhoneByState;
            }

            //校验该证件号是否注册过子工号（同一个身份证不能同时成为同app平台两个商户的子工号）
            String checkIdCard = checkIdCardIsMain(idCard,detailType);
            if (StringUtils.isNotBlank(checkIdCard)) {
                return checkIdCard;
            }

            // 校验身份证号是否存在审核表（在途，该子工号身份证是否正在审核中）
            String checkIdCardForAudit = checkIdCardForAudit(idCard,detailType);
            if (StringUtils.isNotBlank(checkIdCardForAudit)) {
                return checkIdCardForAudit;
            }
            Map<String, String> baseMap = appConfDAO.getConfValuesResMap(OtherConfType.USER_TITLE, detailType);
            String userId = baseMap.get(OtherConfType.USER_TITLE.getConfName()) + getUserId();
            Long nowTime = Clock.systemDefaultZone().millis();
            String orderId = Constant.ADD_JOB_NUM + DateUtils.format(nowTime, "yyMMddHHmmss") + user.getPhone().substring(4);
            JobNumberAudit audit = new JobNumberAudit();
            audit.setOrderId(orderId);
            audit.setUserId(userId);
            audit.setCreateTime(nowTime);
            audit.setSonUserName(name);
            audit.setIdentityCard(idCard);
            audit.setIdentityCardAddress(idAddress);
            audit.setPeriod(period);
            audit.setCityCode(cityCode);
            audit.setCityName(cityName);
            audit.setRelationType(Integer.parseInt(relationType));
            audit.setIdentifyPhotoFront(identifyPhotoFront);
            audit.setIdentifyPhotoReverse(identifyPhotoReverse);
            audit.setIdentifyPhotoHand(identifyPhotoHand);
            audit.setIdentifyPhotoHead(identifyPhotoHead);
            audit.setSignPicture(signPicture);
            audit.setSonUserPhone(phone);
            //无论是卡盟侧、单点结算侧，sourceType都传1。
            // 此处涉及到ams自动审核拒绝，通过redis通知ums的定时任务(使用的老key)。
            audit.setSourceType(Constant.SourceType.KAMENG);
            audit.setMerchantType(merchant.getMerchantType()); // 个人
            audit.setOrderStatus(3); // 待分配
            audit.setImgSource(Integer.parseInt(Constant.UPLOAD_IMG_CONFIG));
            audit.setDoGzt(Constant.DO_GZT); // 国政通开关：1做，2不做
            audit.setIsp("1");
            audit.setOpenModel("1");
            audit.setDetailType(detailType);
            boolean r = sdkAppJobNumberDao.addJobNumberAudit(user, audit);
            if (!r) {
                log.warn("addJobNumberAudit return false," + json);
                return StatusCode.SYSTEM_EXCEPTION.toJSON("系统忙，请稍后再试");
            }

            // 添加子工号需要加入redis自动审核(ams),因为无水印图存在服务器本地，所以需要从本地拿无水印图覆盖原来路径传给AMS(IOS老版本不需要做预审)
            audit.setIdentifyPhotoFront(identifyPhotoFront.replace("_narrow", ""));
            audit.setIdentifyPhotoReverse(identifyPhotoReverse.replace("_narrow", ""));
            audit.setIdentifyPhotoHand(identifyPhotoHand.replace("_narrow", ""));
            audit.setIdentifyPhotoHead(identifyPhotoHead.replace("_narrow", ""));
            final String auditStr = JSONObject.toJSONString(audit);
            Long result = sdkAppJobNumberDao.redis_rpush(RedisConstant.ADD_SON_JOB_NUM_AUDITED_KEY, auditStr);
            if (result == null) {
                log.error("redis连接异常");
                return StatusCode.SYSTEM_EXCEPTION.toJSON();
            }
            log.info("添加子工号预审： Redis(AMS) KEY:" + RedisConstant.ADD_SON_JOB_NUM_AUDITED_KEY + ",val:" + auditStr);

            return StatusCode.SUCCESS.toJSON();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return StatusCode.SYSTEM_EXCEPTION.toJSON();
        } finally {
            sdkAppJobNumberDao.redis_del(keyLock);
        }
    }

    @Override
    public String getCreateCode(ServerRequest request) {
        try {
            JSONObject json = (JSONObject)request.getAttribute("json");
            User user = (User)request.getAttribute("user");
            UserToken ut = (UserToken)request.getAttribute("userToken");
            int detailType = user.getDetailType();
            String appId = ut.getAppId();

            final String phone = json.getString("phone");
            final String idCard = json.getString("idCard");
            if (phone == null || phone.length() != 11) {
                return StatusCode.PARAM_ERROR.toJSON("电话号码错误");
            }
            if (idCard != null && idCard.length() == 0) {
                return StatusCode.PARAM_ERROR.json().msg("证件号未上传").toString();
            }
            if (user.getIsMain() != 1) {
                log.warn("非主工号 removeUser");
                return StatusCode.PERMISSIONPROFILE_IS_NULL.toJSON();
            }
            User userDB = sdkAppJobNumberDao.getJobnumberUserByPhone(phone,detailType);
            String checkPhone = checkPhone(phone, userDB);
            if (checkPhone != null) {
                return checkPhone;
            }
            if (ObjectUtils.nonNullOrEmpty(idCard)) {
                String checkIdCardBlack = checkIdCardIsBlack(idCard);
                if (checkIdCardBlack != null) {
                    return checkIdCardBlack;
                }
            }

            Merchant merchant = merchantDAO.getByMerchantId(user.getMerchantId());
            if (Objects.isNull(merchant)) {
                log.error("DB 连接异常，merchantId=" + user.getMerchantId());
                return StatusCode.SYSTEM_EXCEPTION.toJSON();
            }

            // 校验存在几个工号(包括在途、主工号)
            String checkSonJobNumCount = checkSonJobNumCount(user.getMerchantId(), merchant.getMerchantType(),appId);
            if (StringUtils.isNotBlank(checkSonJobNumCount)) {
                return checkSonJobNumCount;
            }

            // 校验手机号是否已经注册过（在途）
            String checkPhoneByState = checkPhoneZaiTu(phone,detailType);
            if (StringUtils.isNotBlank(checkPhoneByState)) {
                return checkPhoneByState;
            }

            //校验该证件号是否注册过子工号
            String checkIdCard = checkIdCardIsMain(idCard, user.getDetailType());
            if (StringUtils.isNotBlank(checkIdCard)) {
                return checkIdCard;
            }

            // 校验身份证号是否存在审核表
            String checkIdCardForAudit = checkIdCardForAudit(idCard,detailType);
            if (StringUtils.isNotBlank(checkIdCardForAudit)) {
                return checkIdCardForAudit;
            }
            String key = user.getUserId() + phone;
            Long t = sdkAppJobNumberDao.redis_ttl(RedisConstant.REDIS_NAME_SPACE + key);
            if (t == null || t < 20) {
                String code = StringUtil.randomNumberString(6);
                if (Constant.IS_TEST) {
                    log.info("测试环境，验证码写死");
                    code = "666666";
                }
                String content = "尊敬的用户,您手机号的开户验证码为：" + code + "。";
                boolean s = sendMsg(phone, content);
                if (!s) {
                    return StatusCode.SYSTEM_EXCEPTION.toJSON("验证码发送失败，请稍候再试");
                }
                sdkAppJobNumberDao.redis_set(RedisConstant.REDIS_NAME_SPACE + key, code);
                sdkAppJobNumberDao.redis_expire(RedisConstant.REDIS_NAME_SPACE + key, 120);

            }
            return StatusCode.SUCCESS.toJSON();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return StatusCode.SYSTEM_EXCEPTION.toJSON();
        }
    }

    @Override
    public String getJobNumberUserDetailList(ServerRequest request) {
        JSONObject json = (JSONObject)request.getAttribute("json");
        final String userId = json.getString("requestUserId");
        if (StringUtils.isBlank(userId)) {
            log.warn("param userId is null");
            return StatusCode.PARAM_ERROR.toJSON("商户ID不能为空");
        }

        UserDetailModel detailModel = sdkAppJobNumberDao.getUserDetailList(userId);
        if (Objects.isNull(detailModel)) {
            log.error("DB connection exception,userId is " + userId);
            return StatusCode.SYSTEM_EXCEPTION.toJSON();
        }

        return StatusCode.SUCCESS.toDiyJson(true, "data", JSONObject.toJSONString(detailModel));

    }

    @Override
    public String getSonJobNumProtocol(ServerRequest request) {
        JSONObject json = (JSONObject)request.getAttribute("json");
        User user = (User)request.getAttribute("user");
        String userId = json.getString("staffUserId");
        if (StringUtils.isBlank(userId)) {
            userId = user.getUserId();
        }
        SonJobNumProtocolModel model = sdkAppJobNumberDao.getSonJobNumProtocol(userId);
        if (Objects.isNull(model)) {
            log.error("DB:getSonJobNumProtocol is null,userId=" + userId);
            return StatusCode.SYSTEM_EXCEPTION.toJSON();
        }
        Merchant merchant = sdkAppJobNumberDao.getMerchantById(user.getMerchantId());
        if (Objects.nonNull(merchant)) {
            model.setMainUserName(merchant.getCompanyName());
        }

        return StatusCode.SUCCESS.toDiyJson(true, "data", JSONObject.toJSONString(model));

    }

    @Override
    public String removeUser(ServerRequest request) {
        try {
            User user = (User) request.getAttribute("user");
            JSONObject json = (JSONObject) request.getAttribute("json");
            final String removeUserId = json.getString("removeUserId");
            if (StringUtil.isNULL(removeUserId)) {
                log.warn("param removeUserId error");
                return StatusCode.PARAM_ERROR.toJSON("参数 工号 错误");
            }
            if (user.getIsMain() != 1) {
                log.warn("非主工号 removeUser");
                return StatusCode.PERMISSIONPROFILE_IS_NULL.toJSON();
            }

            User removeUser = userDAO.getUser(removeUserId);
            if (removeUser == null) {
                log.warn("getUser return null,userid:" + removeUserId);
                return StatusCode.STAFF_NOT_FOUND.toJSON();
            }
            if (Constant.remove_with_account == 2) {
                if (removeUser.getLeftFee() != 0) {
                    log.warn("有余额不允许删除子工号");
                    return StatusCode.NO_AUTHORITY.toJSON("此工号内仍有余额，不允许删除。");
                }
            }
            if (!removeUser.getDealerId().equals(user.getDealerId())) {
                log.warn("非统一商户号");
                return StatusCode.NO_AUTHORITY.toJSON("不允许删除其他商户子工号");
            }
            if (removeUser.getIsMain() == 1) {
                log.warn("主工号，" + removeUserId);
                return StatusCode.NO_AUTHORITY.toJSON("主账号不允许删除");
            }
            Long left_fee = userDAO.getLeftFee(user.getUserId());
            if (left_fee == null) {
                log.warn("getLeftFee return null,userid:" + user.getUserId());
                return StatusCode.SYSTEM_EXCEPTION.toJSON();
            }
            user.setLeftFee(left_fee);
            String order_id = "DE" + createSysOrderId();
            // 用户的删除标志
            removeUser.setFlag(Flag.DELETED);
            Boolean r = userDAO.removeUser(removeUser, user, order_id);
            if (r == null || r.equals(false)) {
                log.warn("removeUser return " + r + "," + r.toString());
                return StatusCode.SYSTEM_EXCEPTION.toJSON("系统繁忙，请稍候再试");
            }
            //同步单点结算侧数据库
            Boolean b =  sendJobNumberRemoveDataToMq(removeUser, user, order_id);
            log.info(String.format("工号授权删除子工号，同步订单号为{%s}的订单数据至单点结算侧DB{%s}。", order_id, (b ? "success" : "error")));

            String content = "您的工号已被删除,账户余额" + new BigDecimal(removeUser.getLeftFee()).divide(new BigDecimal(100), 2)
                    + "元已转入主工号" + user.getUserName() + "(电话:" + user.getPhone() + ")中。";
            sendMsg(removeUser.getPhone(), content);
            return StatusCode.SUCCESS.toJSON();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return StatusCode.SYSTEM_EXCEPTION.toJSON();
        }
    }

    private Boolean sendJobNumberRemoveDataToMq(User removeUser, User user, String order_id) {
        try {
            MqBody mqBody = new MqBody();
            JSONObject obj = new JSONObject();
            Integer detailType = user.getDetailType();
            //查询appId
            SdkAppConfModel model = userDAO.getAppIdByDetailType(detailType);
            obj.put("appId",model.getAppId());
            obj.put("type",SyncDataType.APP_REMOVE_JOBNUMBER_SUCCESS.getType());
            obj.put("uniqueId",order_id);

            mqBody.setUniqueId(order_id);
            RemoveJobNumberMqInfo removeJobNumberMqInfo = getMqInfo(removeUser,user,model,order_id);
            obj.put("data",JSONObject.parseObject(JSONObject.toJSONString(removeJobNumberMqInfo)));
            mqBody.setBody(obj);
            sendDataToConnectorMQ(mqBody,SyncDataType.APP_REMOVE_JOBNUMBER_SUCCESS.getType());
            return true;
        } catch (Exception e) {
            log.info(String.format("工号授权删除子工号,同步订单号为{%s}的数据失败，原因：{%s}",order_id,e));
            return false;
        }
    }

    private RemoveJobNumberMqInfo getMqInfo(User removeUser, User user, SdkAppConfModel model, String order_id) {
        RemoveJobNumberMqInfo info = new RemoveJobNumberMqInfo();
        long nowTime = System.currentTimeMillis();
        info.setRemoveFlag(removeUser.getFlag());
        info.setRemoveUserid(removeUser.getUserId());
        info.setRemoveDealerid(removeUser.getDealerId());
        info.setCreateTime(nowTime);



        return info;
    }

    protected String createSysOrderId() {
        return DateUtils.format(Clock.systemDefaultZone().millis(), "yyMMddHHmmss") + StringUtil.randomNumberString(6);
    }

    private String checkIdCardForAudit(String idCard, int detailType) {
        if (ObjectUtils.isNullOrEmpty(idCard)) {
            return null;
        }
        JobNumberAudit audit = sdkAppJobNumberDao.getJobNumAuditByIdCard(idCard,detailType);
        if (Objects.nonNull(audit)) {
            log.info(idCard + "证件号正在审核中，" + audit.getOrderId());
            return StatusCode.USERNAME_EXISTED.json().msg("该证件号正在审核中，请更换证件").toString();
        }
        return null;
    }

    private String checkIdCardIsMain(String idCard, int detailType) {
        if (ObjectUtils.isNullOrEmpty(idCard)) {
            return null;
        }
        User user = sdkAppJobNumberDao.getUserByIdCardIsMain(idCard, detailType, 0);
        if (Objects.nonNull(user)) {
            log.info(idCard + "证件号已有用户，" + user.getUserId());
            return StatusCode.USERNAME_EXISTED.json().msg("该证件号正在被工号使用中，请更换证件").toString();
        }
        return null;
    }

    private String checkPhoneZaiTu(String phone,int detailType) {
        List<JobNumberAuditModel> jobNumberAuditList = sdkAppJobNumberDao.checkZaiTu(phone,detailType);
        if (Objects.nonNull(jobNumberAuditList) && jobNumberAuditList.size() > 0) {
            log.warn(phone + " be used");
            return StatusCode.USERNAME_EXISTED.toJSON("该手机号码正在子工号审核中，请更换手机号码");
        }
        return null;
    }

    private String checkPhone(String phone, User user) {
        if (Objects.isNull(user)) {
            log.error("DB连接异常");
            return StatusCode.SYSTEM_EXCEPTION.toJSON("网络异常");
        }
        if (Objects.isNull(user.getUserId())) {
            return null;
        }else{
            log.warn(phone + " be used");
            return StatusCode.USERNAME_EXISTED.toJSON("该手机号码不可用，请更换手机号码");
        }

    }

    private String checkIdCardIsBlack(String idCard) {
        // 判断身份证黑名单
        final boolean res = blackIdCardDAO.idCardUsed(idCard);
        if (!res) {
            log.error("商户被加入身份证名单tb_black_idcard,idCard=" + idCard);
            return StatusCode.SYSTEM_EXCEPTION.toJSON("身份证异常,请联系管理员");
        }
        return null;
    }

    private String checkSonJobNumCount(String merchantId, int merchantType,String appId) {
        // 判断已经存在工号和在途子工号一共有多少个
        //获取已添加的子工号总数(主+子)
        int count = 0;
        List<UserDataModel> userList = sdkAppJobNumberDao.getJobNumberUserList(merchantId);
        if (Objects.nonNull(userList)) {
            count += userList.size();
        }
        //获取正在审核中的子工号数量
        List<JobNumberAuditModel> jobNumberAuditList = sdkAppJobNumberDao.getJobNumberAuditList(merchantId, 1);
        if (Objects.nonNull(jobNumberAuditList)) {
            count += jobNumberAuditList.size();
        }
        //根据appId去tb_sdk_app_conf表查询对应app配置的工号限制数量(企业、个人之分)
        JobNumberCountInfo info = sdkAppJobNumberDao.getJobNumberCountInfo(appId);
        if(ObjectUtils.isNull(info.getCompanyJobNumberCount())
                || ObjectUtils.isNull(info.getPersonalJobNumberCount())){
            return StatusCode.SYSTEM_CONFIG_ERROR.toJSON();
        }
        if (merchantType == 1) {
            // 企业
            if (count >= Integer.valueOf(info.getCompanyJobNumberCount())) {
                log.error("该用户子工号达到上限,dealerId为" + merchantId);
                return StatusCode.SYSTEM_EXCEPTION.toJSON("该用户子工号达到上限,如需操作请联系管理员");
            }
        } else {
            // 个人
            if (count >=Integer.valueOf(info.getPersonalJobNumberCount())) {
                log.error("该用户子工号达到上限,dealerId为" + merchantId);
                return StatusCode.SYSTEM_EXCEPTION.toJSON("该用户子工号达到上限,如需操作请联系管理员");
            }
        }
        return null;

    }
}
